package com.szlanyou.tcp_client_demo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.tcpclientmaster.TcpSocketClient;
import com.szlanyou.protocol_service.LogUtil;
import com.szlanyou.protocol_service.ProtocolHandler;
import com.szlanyou.protocol_service.Singleton;

import java.io.InputStream;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tvState;
    private boolean isConnected = false;
    private TextView tvRecMsg;
    private TcpSocketClient socketClient;
    private Singleton<ProtocolHandler> protocolHandlerSingleton;
    private TextView btnControl;
    private StringBuffer cmdSb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cmdSb = new StringBuffer();
        initView();
        initSocketClient();
    }

    private void initSocketClient() {
        socketClient = new TcpSocketClient(this);
        protocolHandlerSingleton = new Singleton<ProtocolHandler>() {
            @Override
            protected ProtocolHandler create() {
                return new ProtocolHandler();
            }
        };
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        tvState = findViewById(R.id.tv_state);
        tvRecMsg = findViewById(R.id.tv_rec_msg);
        btnControl = findViewById(R.id.btn_control);
        initToolBar();
    }

    private void initToolBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toolbar.setTitle(R.string.app_name);
            setSupportActionBar(toolbar);
        }
    }

    private void connnectServer() {
        protocolHandlerSingleton.get().setOnDecodeListener(new ProtocolHandler.OnDecodeListener() {
            @Override
            public void onDecoded(final String oneFrameData) {
                LogUtil.d("收到服务端的消息：" + oneFrameData);
                refreshCmds("<<收到服务端的消息：" + oneFrameData);

            }

            @Override
            public void onReadException(Throwable e) {
                LogUtil.e("读取流异常");
                e.printStackTrace();
            }
        });
        socketClient.setOnClientStatusListener(new TcpSocketClient.OnClientStatusListener() {
            @Override
            public void onRead(InputStream in) {
                protocolHandlerSingleton.get().handle(in);
            }

            @Override
            public void onConnecting() {
                LogUtil.d("正在连接");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       tvState.setText("正在连接");
                    }
                });
            }

            @Override
            public void onConnected() {
                LogUtil.d("连接成功");
                isConnected = true;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvState.setText("连接成功");
                        btnControl.setText("断开连接");
                    }
                });
                protocolHandlerSingleton.get().start();
            }

            @Override
            public void onConnectFailed(final Throwable e) {
                LogUtil.d("连接失败：" + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvState.setText("连接失败：" + e.getMessage());
                        btnControl.setText("连接");
                    }
                });
            }

            @Override
            public void onError(final Throwable e) {
                LogUtil.d("异常：" + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvState.setText("异常：" + e.getMessage());
                    }
                });
                protocolHandlerSingleton.get().release();
            }

            @Override
            public void onDisconnect(final Throwable e) {
                LogUtil.d("连接异常断开：" + e.getMessage());
                isConnected = false;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvState.setText("连接异常断开：" + e.getMessage());
                        btnControl.setText("连接");
                    }
                });
                protocolHandlerSingleton.get().release();
            }

            @Override
            public void onDisconnected() {
                LogUtil.d("连接断开");
                isConnected = false;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvState.setText("连接断开");
                        btnControl.setText("连接");
                    }
                });
                protocolHandlerSingleton.get().release();
            }

            @Override
            public void onSendMsgFailure(final Throwable e) {
                LogUtil.d("发送消息失败：" + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvState.setText("发送消息失败：" + e.getMessage());
                    }
                });
            }
        });
//        socketClient.connect("10.14.207.113", 9999);
        socketClient.connect("10.14.207.243", 9999);
        socketClient.setAutoReconnect(true);
    }

    public void connectOrDisConnect(View view) {
        if(isConnected){
            socketClient.stop();
        }else{
            connnectServer();
        }
    }

    public void sendMsg(View view) {
        String cmd = "#{我是客户端" + new Random().nextInt(100) + "}#";
        sendCmd(cmd);
    }

    private void sendCmd(String cmd){
        socketClient.send(cmd);
        refreshCmds(">>发送消息：" + cmd);
    }

    public void checkAlive(View view) {
        Toast.makeText(this, "isAlive:" + socketClient.isAlive(), Toast.LENGTH_SHORT).show();
    }

    /**
     * //TODO 如果是密集的指令，协议处理时要做队列，目前不做处理。
     * @param view
     */
    public void pressureTest(final View view) {
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    String cmd = "#{我是客户端index = " + i + "}#";
                    sendCmd(cmd);
                    SystemClock.sleep(10);
                }
            }
        }.start();
    }

    private void refreshCmds(String cmd){
        cmdSb.append(cmd);
        cmdSb.append("\n");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvRecMsg.setText(cmdSb.toString());
            }
        });
    }

    public void clearLog(View view) {
        cmdSb.setLength(0);
        tvRecMsg.setText(cmdSb.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        protocolHandlerSingleton.get().release();
        socketClient.release();
    }
}